package com.sychip.fhc.app.wsn.screen


import android.content.ContentValues
import android.content.Context
import android.content.res.Configuration
import android.media.MediaScannerConnection
import android.net.Uri
import android.provider.MediaStore
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Camera
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Mail
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.fhc.view.EmailScreen
import com.fhc.view.FhcAnimatedCombinedIcon
import com.fhc.view.FhcBottomSheet
import com.fhc.view.list.ClickableListItem
import com.fhc.view.list.swip.SwipeAction
import com.fhc.view.list.swip.SwipeableActionsBox
import com.fhc.view.list.swip.rememberSwipeableActionsState
import com.fhc.view.rememberFhcBottomSheetVisibleState
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.data.source.dto.WsnTestRecordDto
import com.sychip.fhc.app.wsn.nav.PostToWsnDetail
import com.sychip.fhc.app.wsn.nav.WsnNavigationItem
import com.sychip.fhc.app.wsn.nav.WsnTabNavigationActions
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WsnTestHisScreen(viewModel: WsnTestHisViewModel = hiltViewModel(), navController: NavHostController = rememberNavController()) {

    val deviceItem: @Composable (WsnTestRecordDto) -> Unit = {
        WsnTestRecordItem(dev = it){
            Text(modifier = Modifier.widthIn(max = 120.dp), text = "RSSI:${it.projectName}", style = MaterialTheme.typography.bodySmall )
        }
    }
    val context = LocalContext.current
    val imageUri = remember { mutableStateOf<Uri?>(null) }
    val cameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture(),
        onResult = { success ->
            if (!success || imageUri.value == null) {
                Timber.e("TakePicture !success || imageUri.value == null", )
            }else{
                val privateDir = File(context.filesDir, "photos").apply {
                    if (!exists()) mkdirs()
                }
                // 保存到私有目录
                val privateFile =  try {
                    val inputStream = context.contentResolver.openInputStream(imageUri.value!!)

                    val outputFile = File(privateDir, "${System.currentTimeMillis()}.jpg")
                    FileOutputStream(outputFile).use { output ->
                        inputStream?.copyTo(output)
                    }
                    outputFile
                } catch (e: Exception) {
                    Timber.e("Camera 保存到私有目录:%s", e.message)
                    null
                }

                // 删除公共目录文件
                try {
                    // 删除公共文件
                    context.contentResolver.delete(imageUri.value!!, null, null)

                    // 更新媒体库（Android 10+）
                    MediaScannerConnection.scanFile( context, arrayOf(imageUri.value!!.path), null) { _, _ -> }
                } catch (e: Exception) {
                    Timber.e("Camera 删除公共目录文件,更新媒体库:%s", e.message)
                }

                // 处理私有文件（显示/上传等）
                privateFile?.let { }
            }
        }
    )


    val coroutineScope: CoroutineScope = rememberCoroutineScope()
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val visibleState = rememberFhcBottomSheetVisibleState()

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            FhcTopAppBar(
                title= WsnNavigationItem.NavItem_TestHis.label,
                actions = {
                    IconButton(onClick = {
                        val uri = createTempImageUri(context) // 创建临时文件URI
                        imageUri.value = uri
                        cameraLauncher.launch(uri).also {
                            Timber.e("Camera launch result: $it")
                        }
                    }) {
                        Icon(
                            Icons.Filled.Camera,
                            contentDescription = null,
                            tint = colorScheme.onPrimary
                        )
                    }
                    IconButton(onClick = {
                        visibleState.value = true
                    }) {
                        FhcAnimatedCombinedIcon(Icons.Filled.Mail, Icons.Filled.Settings, colorScheme.onPrimary, Color.Blue)
                    }
                }
            )
        },
    ) { innerPadding ->
        Box(modifier = Modifier
            .padding(top = innerPadding.calculateTopPadding())
            .fillMaxSize()) {
            Box(modifier = Modifier.fillMaxSize()) {
                RssiDataListView(
                    viewModel = viewModel,
                    modifier = Modifier.fillMaxSize(),
                    dataItem = deviceItem,
                    navController = navController
                )
            }
            FhcBottomSheet(title = "邮箱设置",sheetState=sheetState, visibleState = visibleState,coroutineScope=coroutineScope, showActionYes = true, onActionYes = {
                true
            }){
                EmailScreen()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun RssiDataListView(
    viewModel: WsnTestHisViewModel,
    modifier: Modifier = Modifier,
    dataItem: @Composable (WsnTestRecordDto) -> Unit = {
        WsnTestRecordItem(dev = it)
    }, navController: NavHostController = rememberNavController()
) {
    // 当前打开的swipe项索引
    var currentOpenedKey by remember { mutableStateOf<Long?>(null)}


    val testDataFlow by viewModel.testDataFlow.collectAsStateWithLifecycle()

    if (testDataFlow.isEmpty()) {
        RssiEmptyView(modifier = modifier)
    } else {
        val navActions: WsnTabNavigationActions = remember(navController) {WsnTabNavigationActions(navController)}

        val scope = rememberCoroutineScope()

        Column(Modifier.fillMaxSize()) {
            LazyColumn( modifier = modifier, contentPadding = PaddingValues(horizontal = 8.dp, vertical = 16.dp) ) {
                itemsIndexed(testDataFlow, key = { index, item ->  item.fromTime }) { index, item ->
                    val itemKey = item.fromTime
                    val state = rememberSwipeableActionsState()

                    val delete = SwipeAction(
                        icon = rememberVectorPainter(Icons.Default.Delete),
                        tintColor = colorScheme.error,
                        background = Color.White.copy(alpha = 0.5f),
                        onClick = {
                            viewModel.delete(itemKey)
                        },
                    )

                    // 状态同步逻辑
                    LaunchedEffect(currentOpenedKey) {
                        scope.launch{
                            if (currentOpenedKey != itemKey) {
                                state.handleReset()  // state.offsetState.floatValue = 0f   //关闭swipe，没有动画
                            }
                        }
                    }

                    SwipeableActionsBox(
                        state = state,
                        endActions = listOf(delete),
                        swipeThreshold = 80.dp,
                        onDragStopped = {},
                        onDragStarted = {it->
                            currentOpenedKey = itemKey
                        }
                    ) {
                        ClickableListItem(
                            item = item,
                            itemView = dataItem,
                            onClick = {
                                val param = PostToWsnDetail("", "", item.fromTime, item.toTime)
                                navActions.navigateToWsnTestHisDetail(param)
                                MainApplication.instance().showBottomNavbar(false)
                            }
                        )
                    }
                    // 添加分隔线
                    HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
                }
            }
        }

    }
}


@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true)
@Composable
private fun WsnTestRecordItem(
    modifier: Modifier = Modifier,
    dev: WsnTestRecordDto= WsnTestRecordDto(),
    extras: @Composable () -> Unit = {},
) {
    Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
        Box(modifier = Modifier
            .size(30.dp, 30.dp)
            .clip(RoundedCornerShape(15.dp))
            .background(Color.Red))
        Spacer(modifier = Modifier.width(16.dp))
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            Text( text = "${dev.fromTime} -->  ${dev.toTime}",  color = colorScheme.onPrimaryContainer, style = MaterialTheme.typography.titleMedium )
            Spacer(modifier = Modifier.height(8.dp))
            Text( text = "Time: ${dev.routeName}",  color = colorScheme.onPrimaryContainer.copy(alpha = 0.8f),  style = MaterialTheme.typography.bodyMedium )
        }
        extras()
    }
}


// Helper function to create temporary image URI
private fun createTempImageUri(context: Context): Uri {
    val contentValues = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, "temp_photo.jpg")
        put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
    }
    return context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)!!
}


